import RegrystGet
import logging
import subprocess
import winreg
import RightGet
import wmi
from Login import *

##############
#author:张子路#
##############

class BackDoorDetect():
    def __init__(self):
        try:
            self.RegistLink=RegrystGet.RegrystGet()         #连接注册表获取python文件
        except Exception as e:
            logging.error("连接文件RegrystGet.py失败 {0}".format(e), exc_info=True)
        self.wmiobj = wmi.WMI()

    def CmdRun(self,cmd):
        try:
            res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)    #运行cmd命令
            for line in res.communicate():
                return(line.decode("GBK"))
        except Exception as e:
            logging.error("执行获取账户信息命令失败 {0}".format(e), exc_info=True)

    def ShadowAccount(self):
        try:
            self.RightsGetLink=RightGet.RightsGet()        #调用获取注册项读取权限的python文件
            self.RightsGetLink.RegistryRightsGet('hklm\SAM\SAM','S-1-5-32-544')    #获取注册项读取权限
        except Exception as e:
            logging.error("连接文件RightGet.py获取注册表权限失败 {0}".format(e), exc_info=True)
        try:
            RegistryKeyDict={winreg.HKEY_LOCAL_MACHINE:[r'SAM\SAM\Domains\Account\Users\Names']}
            RegistSearchResult=self.RegistLink.RegistryKeyGet(RegistryKeyDict)    #获取注册表项
        except Exception as e:
            logging.error("获取注册表项失败 {0}".format(e), exc_info=True)
        try:
            Account=[]
            UserAccount = self.wmiobj.Win32_UserAccount()        #获取系统中存在的用户
            for iteam in UserAccount:
                Account.append(iteam.Name)
        except Exception as e:
            logging.error("执行获取账户信息命令失败 {0}".format(e), exc_info=True)
        try:
            ShadowAccount=[]
            for iteam in Account:     #对比得出影子账户
                IsShadow=True
                for Normaliteam in RegistSearchResult:
                    if iteam==Normaliteam:
                        IsShadow=False
                        break
                if IsShadow==True:
                    ShadowAccount.append(iteam)
        except Exception as e:
            logging.error("账户比对失败 {0}".format(e), exc_info=True)
        try:
            return ShadowAccount           #输出影子账户
        except Exception as e:
            logging.error("影子账户查询结果返回失败 {0}".format(e), exc_info=True)


if __name__ == '__main__':
    login=LoginStart()
    login.start()